package com.bj.zspace;

import com.bjzspace.proto.TestProto;
import com.bjzspace.proto.TestServiceGrpc;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.junit.Test;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class GrpcClient2 {

    @Test
    public void testBlock(){
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("127.0.0.1", 9999).usePlaintext().build();
        try{
            TestServiceGrpc.TestServiceFutureStub testService = TestServiceGrpc.newFutureStub(managedChannel);
            ListenableFuture<TestProto.TestResponse> listenableFuture = testService.test(TestProto.TestRequest.newBuilder().setName("test lwq").build());
            TestProto.TestResponse testResponse = listenableFuture.get(2000, TimeUnit.MILLISECONDS);
            System.out.println(testResponse.getResult());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            managedChannel.shutdown();
        }
    }

    @Test
    public void testListener(){
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 9999).usePlaintext().build();

        try{
            TestServiceGrpc.TestServiceFutureStub testServiceFutureStub = TestServiceGrpc.newFutureStub(managedChannel);
            ListenableFuture<TestProto.TestResponse> listenableFuture =
                testServiceFutureStub.test(TestProto.TestRequest.newBuilder().setName("client send").build());
            /*listenableFuture.addListener(() -> {
                System.out.println("listenable over");
            }, Executors.newFixedThreadPool(1));*/
            Futures.addCallback(listenableFuture, new FutureCallback<TestProto.TestResponse>() {
                @Override
                public void onSuccess(TestProto.TestResponse result) {
                    System.out.println("client receive:" + result.getResult());
                }
                @Override
                public void onFailure(Throwable t) {
                    System.out.println("onFailure:" + t.getMessage());
                }
            }, Executors.newFixedThreadPool(1));
            System.out.println("listenable add Listener");
            System.in.read();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            managedChannel.shutdown();
        }



    }

}
